from rest_framework.decorators import action
from rest_framework.viewsets import ViewSet
from rest_framework.permissions import IsAuthenticated
from course.models import Course
from rest_framework.response import Response
from rest_framework import status
from django_redis import get_redis_connection
import logging

log = logging.getLogger("django")

class CartAPIView(ViewSet):

    """购物车"""
    # permission_classes = [IsAuthenticated]
    @action(methods=["POST"], detail=False)
    def add(self,request):
        """添加商品到购物车中"""
        # 接受客户端提交参数[用户ID，课程ID，勾选状态，有效期选项]
        course_id = request.data.get("course_id")
        user_id = request.user.id
        # 设置默认值
        selected = True
        expire = 0
        # 校验参数
        try:
            course = Course.objects.get(is_show=True, is_deleted=False, id=course_id)
        except Course.DoesNotExist:
            return Response({"message":"参数有误！课程不存在！"}, status=status.HTTP_400_BAD_REQUEST)

        # 获取redis连接对象
        redis_conn = get_redis_connection("cart")
        # 保存数据到redis
        try:
            pipe = redis_conn.pipeline()
            pipe.multi()
            # 哈希存储
            pipe.hset("cart_%s" % user_id, course_id, expire)
            # 集合存储
            pipe.sadd("selected_%s" % user_id, course_id)
            pipe.execute()

            # 查询购物车中商品总数
            course_len = redis_conn.hlen("cart_%s" % user_id)
            print("商品数量===",course_len)
        except:
            log.error("购物车数据存储错误！")
            return Response({"message": "参数有误！购物车添加商品失败！"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)



        # 返回结果[当前购物车中商品总数]
        return Response({"message":"购物车商品添加成功！","length": course_len})

    # 获取购物车中的数据
    @action(methods=["get"], detail=False)
    def get(self, request):
        """购物车商品列表"""
        user_id = 1  # request.user.id
        redis = get_redis_connection("cart")
        # 从hash里面读取购物车基本信息
        cart_course_list = redis.hgetall("cart_%s" % user_id)
        # 从set集合中查询所有已经勾选的商品ID
        cart_selected_list = redis.smembers("selected_%s" % user_id)

        # 如果提取到的商品购物车信息为空！，则直接返回空列表
        if len(cart_course_list) < 1:
            return Response([])

        data = []

        # 苟泽我们就要组装商品课程新返回给客户端
        for course_bytes, expire_bytes in cart_course_list.items():
            # print("课程ID", course_bytes)
            # print("有效期", expire_bytes)
            course_id = course_bytes.decode()
            try:
                course = Course.objects.get(pk=course_id)
            except Course.DoesNotExist:
                # 当前商品不存在！
                pass

            data.append({
                "id": course_id,
                "name": course.name,
                # "course_img": settings.DOMAIL_IMAGE_URL + course.course_img.url,
                "price": course.price,
                "is_selected": True if course_bytes in cart_selected_list else False
            })

        return Response(data)